import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#从fbprophet库中导入Prophet类
from fbprophet import Prophet


def read_data(file_path):
    data = pd.read_csv(file_path)
    data['DateValue'] = pd.to_datetime(data['DateValue'], format='%Y-%m-%d')
    data['Quantity'] = pd.to_numeric(data['Quantity'])
    #预处理数据，把DateValue列改名为ds，Quantity列改名为y
    data = data.rename(columns = {"DateValue":"ds", "Quantity":"y"})[["ds","y"]]
    return data


def prophet_model(data):
    #创建Prophet模型
    model = Prophet(yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True)
    #添加节假日
    model.add_country_holidays(country_name="CN")
    #拟合数据
    model.fit(data)
    return model
    
def prophet_predict(model,forecast_file_path,fbImg_file_path):

    #设置未来时间点
    future = model.make_future_dataframe(periods=62,freq='D',include_history=False)
    #预测
    forecast = model.predict(future)
    #输出图表
    fbplot=model.plot(forecast)
    fbplot.savefig(fbImg_file_path)
    #存储预测数据文件
    if(os.path.exists(forecast_file_path)):
        os.remove(forecast_file_path)
    forecast.to_csv(forecast_file_path)
    return forecast

def read_forecast_data(forecast_file_path):
    df = pd.read_csv(forecast_file_path)
    df = df.rename(columns={'ds': 'ds', 'y': 'yhat'})
    return df
    
    
def read_fact_data(fact_file_path):
    df_real = pd.read_csv(fact_file_path)
    return df_real
  
 #绘制图表  
def plot_data(df_real,df_forecast,image_file_path,businessId):
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定中文字体
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示为方块的问题
    #tuple[Figure,Axes],fig不能省略
    fig,ax=plt.subplots()
    fig=plt.gcf()
    ax.plot(df_forecast.ds,df_forecast.yhat,label='forecast')
    ax.plot(df_real.DateValue,df_real.Quantity,label='fact')

    #设置图表标题与轴标签
    ax.set(xlabel='date',ylabel='value',title=f'{businessId} 日期-销量')

    #设置x轴的日期格式
    plt.xticks(rotation=45)
    # 添加图例
    plt.legend()
    #显示图表
    plt.show()
    #保存图表
    if(os.path.exists(image_file_path)):
        os.remove(image_file_path)
        
    #plt.savefig(image_file_path)
    fig.savefig(image_file_path)

#fb 预测数据与预测数据与实际数据绘图
def fb_prophet_draw(dataList,fact_file_path,forecast_file_path,image_file_path,businessId,fbImg_file_path):
    # 将所有数据合并到一个 DataFrame 中
    combined_data = pd.concat(dataList, ignore_index=True)

    #初始化模型
    model=prophet_model(combined_data)

    #预测
    prophet_predict(model,forecast_file_path,fbImg_file_path)

    #读取预测结果
    df_forecast=read_forecast_data(forecast_file_path)

    #读取事实数据
    df_fact=read_fact_data(fact_file_path)

    #绘图
    plot_data(df_fact,df_forecast,image_file_path,businessId=businessId)